package com.mm.cloth.utils;

import android.content.Context;
import android.util.Log;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 全局异常处理器
 * 用于捕获和记录应用崩溃信息
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    
    private static final String TAG = "CrashHandler";
    private static CrashHandler instance;
    private Context context;
    private Thread.UncaughtExceptionHandler defaultHandler;
    
    private CrashHandler() {}
    
    public static CrashHandler getInstance() {
        if (instance == null) {
            instance = new CrashHandler();
        }
        return instance;
    }
    
    public void init(Context context) {
        this.context = context;
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        Log.d(TAG, "CrashHandler初始化完成");
    }
    
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        Log.e(TAG, "=== 应用崩溃 ===");
        Log.e(TAG, "线程: " + thread.getName());
        Log.e(TAG, "异常类型: " + ex.getClass().getName());
        Log.e(TAG, "异常消息: " + ex.getMessage());
        
        // 获取详细的堆栈跟踪
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        String stackTrace = sw.toString();
        
        Log.e(TAG, "完整堆栈跟踪:");
        Log.e(TAG, stackTrace);
        
        // 记录崩溃时的系统信息
        Log.e(TAG, "=== 系统信息 ===");
        Log.e(TAG, "Android版本: " + android.os.Build.VERSION.RELEASE);
        Log.e(TAG, "API级别: " + android.os.Build.VERSION.SDK_INT);
        Log.e(TAG, "设备型号: " + android.os.Build.MODEL);
        Log.e(TAG, "设备制造商: " + android.os.Build.MANUFACTURER);
        
        // 记录内存信息
        Runtime runtime = Runtime.getRuntime();
        long maxMemory = runtime.maxMemory();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        long usedMemory = totalMemory - freeMemory;
        
        Log.e(TAG, "=== 内存信息 ===");
        Log.e(TAG, "最大内存: " + (maxMemory / 1024 / 1024) + "MB");
        Log.e(TAG, "总内存: " + (totalMemory / 1024 / 1024) + "MB");
        Log.e(TAG, "已用内存: " + (usedMemory / 1024 / 1024) + "MB");
        Log.e(TAG, "可用内存: " + (freeMemory / 1024 / 1024) + "MB");
        
        Log.e(TAG, "=== 崩溃信息记录完成 ===");
        
        // 调用系统默认的异常处理器
        if (defaultHandler != null) {
            defaultHandler.uncaughtException(thread, ex);
        }
    }
}
